<template>
  <view class="big2" v-if="!resShow">
    <view class="tableA">
      <nut-cell title="发货地" :desc="addressFilter(props.mainState.sendAddress) || '请选择发货地'" @click="showPop" is-link>
        <template v-slot:icon>
          <view class="sendImg"></view>
        </template>
      </nut-cell>
      <nut-cell title="收货地" :desc="addressFilter(props.mainState.getAddress) || '请选择收货地'" @click="showPop2" is-link>
        <template v-slot:icon>
          <view class="getImg"></view>
        </template>
      </nut-cell>
      <nut-cell title="网点" :desc="formState.WDAddress.toString() || '请选择网点'" @click="chooseWD()" is-link>
        <template v-slot:icon>
          <view class="WDImg"></view>
        </template>
      </nut-cell>
    </view>
    <view class="tableB">
      <nut-cell title="货物重量">
        <template v-slot:link>
          <view class="countBox">
            <nut-input-number min="0" step="0.01" decimal-places="2" v-model="formState.weight" />
          </view>
          <view style="font-weight: 600; color: black; width: 80rpx">&nbsp;&nbsp;&nbsp;Kg</view>
        </template>
      </nut-cell>
      <nut-cell title="货物数量">
        <template v-slot:link>
          <view class="countBox">
            <nut-input-number :disabled="exact" min="0" v-model="formState.number" />
          </view>
          <view style="font-weight: 600; color: black; width: 80rpx">&nbsp;&nbsp;&nbsp;件</view>
        </template>
      </nut-cell>
      <nut-cell title="货物体积">
        <template v-slot:link>
          <view class="countBox">
            <nut-input-number :disabled="exact" step="0.01" decimal-places="2" min="0" v-model="formState.volume" />
          </view>
          <view style="font-weight: 600; color: black; width: 80rpx">&nbsp;&nbsp; m³</view>
        </template>
      </nut-cell>
      <view class="check-exact">
        <view style="margin-right: 16rpx">规则计算预估费用更准确</view>
        <nut-switch v-model="exact" active-color="#0966ff" />
      </view>
      <!--      <nut-cell title="货物规格" :desc="formState.cargo || '请完善货物规格信息'" @click="addressShow.goodShow = true" is-link>-->
      <!--      </nut-cell>-->
      <view class="goods_specifications" v-if="exact">
        <view class="goods_specifications_list" v-for="(item, index) in specifications" :key="index">
          <view class="goods_specifications_list_div" style=" margin-left: 24rpx;">
            <nut-input placeholder="长" v-model="item.l" type="number"
              @input="item.l = item.l.replace(/^(0+)|[^\d]+/g, '')" input-align="center" />
            <view class="d">cm</view>
          </view>
          <view class="icon">x</view>
          <view class="goods_specifications_list_div">
            <nut-input placeholder="宽" v-model="item.w" type="number"
              @input="item.w = item.w.replace(/^(0+)|[^\d]+/g, '')" input-align="center" />
            <view class="d">cm</view>
          </view>
          <view class="icon">x</view>
          <view class="goods_specifications_list_div">
            <nut-input placeholder="高" v-model="item.h" type="number"
              @input="item.h = item.h.replace(/^(0+)|[^\d]+/g, '')" input-align="center" />
            <view class="d">cm</view>
          </view>
          <view class="icon">x</view>
          <view class="goods_specifications_list_div">
            <nut-input placeholder="件数" v-model="item.sum" type="number"
              @input="item.sum = item.sum.replace(/^(0+)|[^\d]+/g, '')" input-align="center" />
            <view class="d">件</view>
          </view>
          <view @click="addSpecifications" v-if="index == 0">
            <image src="@/assets/images/index/woyaofahuo_icon_tianjiaguige.png"></image>
          </view>
          <view @click="delSpecifications(index)" v-else>
            <image src="@/assets/images/index/woyaofahuo_icon_shanchuguige.png"></image>
          </view>
        </view>
      </view>
    </view>
    <view class="bottomBoxFE">
      <!--      <nut-button style="margin-top: 16px" color="#0966FF" size="large" type="primary"-->
      <!--        @click="inquire">查&nbsp;&nbsp;询</nut-button>-->
      <view class="mybtn" @click="inquire">查 询</view>
      <p class="bottomP">说明：价格时效仅供参考，具体以实际为准</p>
    </view>
  </view>
  <view v-else>
    <view class="resBox1" v-if="resData.data[0]">
      <view class="resItem resBoxTop">普件</view>
      <view class="resItem bottomBorder">
        <view style="display: flex">
          <image src="../../../assets/images/index/服务查询/shixiaojiage_icon_zuidiyunjia.png" alt="" />
          <p>运费金额</p>
        </view>
        <view class="price">￥&nbsp;&nbsp;{{ resData.data[0].price }}</view>
      </view>
      <view class="resItem">
        <view style="display: flex">
          <image src="../../../assets/images/index/服务查询/shixiaojiage_icon_shixiaomiaoshu.png" alt="" />
          <p>时效描述</p>
        </view>
        <view class="price">{{ resData.data[0].PICKUP_INFO }}</view>
      </view>
    </view>
    <view class="resBox2" v-if="quickData.data[0]">
      <view class="resItem resBoxTop">普件</view>
      <view class="resItem bottomBorder">
        <view style="display: flex">
          <image src="../../../assets/images/index/服务查询/shixiaojiage_icon_zuidiyunjia-2.png" alt="" />
          <p>运费金额</p>
        </view>
        <view class="price">￥&nbsp;&nbsp;{{ resData.data[0].price }}</view>
      </view>
      <view class="resItem">
        <view style="display: flex">
          <image src="../../../assets/images/index/服务查询/shixiaojiage_icon_shixiaomiaoshu-2.png" alt="" />
          <p>时效描述</p>
        </view>
        <view class="price">{{ resData.data[0].PICKUP_INFO }}</view>
      </view>
    </view>
    <view class="bottomBoxFE">
      <!--      <nut-button style="margin-top: 16px" color="#0966FF" size="large" type="primary"-->
      <!--        @click="resShow = false">重新查询</nut-button>-->
      <view class="mybtn" @click="resShow = false">重新查询</view>
      <p class="bottomP">说明：价格时效仅供参考，具体以实际为准</p>
    </view>
  </view>
  <!-- 网点选择 -->
  <WDChoose :addressShow="addressShow" :desBranchList="desBranchList" @chooseBranch="chooseBranch"></WDChoose>
  <!-- 货物选择 -->
  <GoodChoose :addressShow="addressShow" @chooseGood="chooseGood"></GoodChoose>
  <!-- 提示弹框 -->
  <!-- <nut-notify v-model:visible="dialogShow" :msg="dialogMsg" /> -->
</template>
<script lang="ts" setup>
import Taro from "@tarojs/taro";
import { $get, $post } from "@/@api/index";
import WDChoose from "./WDChoose.vue";
import GoodChoose from "./cargoSpecification.vue";
import { onMounted, ref, reactive, watch } from "vue";
import { type DesBranchList } from '../types'
import { longsPrice, getRecommandBranch } from "@/@api/order";

import dayjs from "dayjs";
//import { GoodsType } from "@/pages3/sendGoods/goodsType";
export interface AddressList {
  code: string;
  children?: AddressList[];
  id: number;
  name: string;
}
const props = defineProps<{
  mainState: any;
  mainShow: any;
  mainShow2: any;
  // dialogErr: any;
}>();
const formState = ref({
  WDAddress: "",
  weight: '',
  volume: '',
  number: '',
  cargo: "",
});
const exact = ref<boolean>(true)
const specifications = ref<object[]>([{
  w: "",
  h: "",
  l: "",
  sum: "  ",
}])

const desBranchList = ref<DesBranchList[]>([]);
const addressShow = ref<{
  WDShow: boolean;
  goodShow: boolean;
}>({
  WDShow: false,
  goodShow: false,
});
const branchNumber = ref(); //选择的网点编号（提交需要）
const resShow = ref(false);
const resData = ref(); //所有查询返回数据
const quickData = ref(); //所有查询返回数据

const emit = defineEmits<{
  (e: "errMsg", errMsg: string);
}>();

function addSpecifications() {
  specifications.value.push({
    w: "",
    h: "",
    l: "",
    sum: "  ",
  });
}
// 货物规格删除
function delSpecifications(index: number) {
  specifications.value.splice(index, 1);
}

// 监听规格触发计算
watch(() => specifications.value, (newVal) => {
  console.log(newVal, '监听')
  let all = 0;
  let sum = 0;
  specifications.value.forEach((item) => {
    all =
      all +
      Number(item.h != "" ? item.h : 0) *
      Number(item.l != "" ? item.l : 0) *
      Number(item.w != "" ? item.w : 0) *
      Number(item.sum != "" ? item.sum : 0);
    sum = sum + Number(item.sum != "" ? item.sum : 0);
  });
  console.log(all, 'all')
  if (all == 0) {
    formState.value.volume = "0";
    formState.value.number = "0";
  } else {
    all = Number((all / 1000000).toFixed(2))
    if (all == 0) {
      formState.value.volume = "0.01";
    } else {
      formState.value.volume = String(all);
    }
    formState.value.number = String(sum);
  }
}, { deep: true, immediate: true })

//查询按钮
async function inquire() {
  if (!props.mainState.sendAddress.length) {
    emit("errMsg", "请选择发货地");

    return;
  }
  if (!props.mainState.getAddress.length) {
    emit("errMsg", "请选择收货地");

    return;
  }
  if (!branchNumber.value) {
    emit("errMsg", "请选择网点");

    return;
  }
  if (!formState.value.volume) {
    emit("errMsg", "请选择货物规格");

    return;
  }
  let sendA = props.mainState.sendAddress.toString().replace(/,/g, " ");
  let getA = props.mainState.getAddress.toString().replace(/,/g, " ");
  // 获取推荐网点 -- 发货
  // const sendRes = await getRecommandBranch({
  //   carriagetype: '送货',
  //   province: props.mainState.sendAddress[0],
  //   city: props.mainState.sendAddress[1],
  //   detailaddress: props.mainState.sendAddress[2],
  // })
  // const sendNo = JSON.parse(sendRes.data.data).branch[0].branchno
  // 获取推荐网点 -- 接货
  const getRes = await getRecommandBranch({
    carriagetype: '送货',
    province: props.mainState.getAddress[0],
    city: props.mainState.getAddress[1],
    detailaddress: props.mainState.getAddress[2]
  })
  const getNo = JSON.parse(getRes.data.data).branch[0].branchno

  // 普件
  const res = await longsPrice({
    startCompany: branchNumber.value,
    descCompany: getNo,
    strarea: sendA,
    desarea: getA,
    volume: formState.value.volume,
    weight: formState.value.weight,
    senddate: dayjs().format('YYYY-MM-DD'),
    type: '普件'
  })

  // 快件
  const res1 = await longsPrice({
    startCompany: branchNumber.value,
    descCompany: getNo,
    strarea: sendA,
    desarea: getA,
    volume: formState.value.volume,
    weight: formState.value.weight,
    senddate: dayjs().format('YYYY-MM-DD'),
    type: '快件'
  })

  if (JSON.parse(res.data.data).code == 1) {
    emit("errMsg", JSON.parse(res.data.data).message);

    return;
  } else {
    resData.value = JSON.parse(res.data.data)
    quickData.value = JSON.parse(res1.data.data)

    resShow.value = true;
  }
}
//选择网点弹框
function chooseWD() {
  if (!props.mainState.sendAddress) {
    emit("errMsg", "请选择发货地");

    return;
  }
  if (!props.mainState.getAddress) {
    emit("errMsg", "请选择收货地");

    return;
  }
  getDesBranchList()
}
async function getDesBranchList() {
  Taro.showLoading({
    title: '加载中',
  })
  try {
    const res = await $get<{ data: string }>("/selfmachine-system/order/recommandBranch", {
      carriagetype: '送货',
      province: props.mainState.sendAddress[0],
      city: props.mainState.sendAddress[1],
      detailaddress: props.mainState.sendAddress[2],
    });
    Taro.hideLoading()
    if (res.statusCode == 200) {
      if (JSON.parse(res.data.data).branch.length > 0) {
        desBranchList.value = JSON.parse(res.data.data).branch;
        addressShow.value.WDShow = true;
      } else {
        emit("errMsg", "暂无网点信息");
      }

    } else {
      desBranchList.value = [];
      emit("errMsg", "暂无网点信息");
    }
  } catch (error) {
    desBranchList.value = []
    emit("errMsg", "暂无网点信息");
  }
}

//地址回显过滤
function addressFilter(add: any) {
  let aa = "";
  for (let i = 0; i < add.length; i++) {
    if (i !== add.length - 1) {
      aa += add[i] + "-";
    } else {
      aa += add[i];
    }
  }
  return aa;
}
//选择网点
function chooseBranch(branchNo: string) {
  branchNumber.value = branchNo;
  desBranchList.value.forEach((item) => {
    if (item.BRANCHCOMPANYNO == branchNo) {
      //formState.value.WDAddress = item.BRANCHCOMPANYNO;
      formState.value.WDAddress = item.COMPANYNAME;
    }
  });
  addressShow.value.WDShow = false;
}
//选择货物规格
function chooseGood(Cargo: any) {
  formState.value.cargo =
    Cargo.goodLength +
    "cm * " +
    Cargo.goodWidth +
    "cm * " +
    Cargo.goodHeight +
    "cm";
  formState.value.volume =
    (Cargo.goodLength * Cargo.goodWidth * Cargo.goodHeight) / 1000000;
  addressShow.value.goodShow = false;
}


const showPop = () => {
  props.mainShow.show = true
}
const showPop2 = () => {
  props.mainShow2.show = true
}
</script>
<style lang="less">
.big2 {
  height: calc(89vh);
  width: 100%;
}

.tableA {
  border-radius: 16rpx;

  .nut-cell {
    margin: 0;
    box-shadow: none;
  }
}

.tableB {
  border-radius: 16rpx;
  margin-top: 16rpx;
  background-color: #fff;
  padding-bottom: 20rpx;

  .nut-cell {
    margin: 0;
    box-shadow: none;
  }

  .check-exact {
    width: 100%;
    box-sizing: border-box;
    padding-right: 32rpx;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-right: 0;
    font-size: 22rpx;
    color: #999;
  }

  .goods_specifications {
    width: 100%;
    margin-top: 16rpx;

    .goods_specifications_list {
      width: 100%;
      height: 80rpx;
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;

      .icon {
        width: 34rpx;
        text-align: center;
      }

      image {
        width: 32rpx;
        height: 32rpx;
        margin-left: 26rpx;
      }

      .goods_specifications_list_div {
        width: 124rpx;
        height: 64rpx;
        background: #f5f5f5;
        display: flex;
        align-items: center;

        .nut-input {
          padding: 0;
          width: 80rpx;
          background-color: unset;
        }

        .d {
          height: 100%;
          width: 44rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          font-family: PingFangSC-Regular;
          font-size: 24rpx;

          color: #666666;
        }
      }
    }
  }
}

.sendImg {
  height: 40rpx;
  width: 40rpx;
  background: url("../../../assets/images/index/服务查询/shixiaojiage_icon_fahuodi.png") no-repeat;
}

.getImg {
  height: 40rpx;
  width: 40rpx;
  background: url("../../../assets/images/index/服务查询/shixiaojiage_icon_shouhuodi.png") no-repeat;
}

.WDImg {
  height: 40rpx;
  width: 40rpx;
  background: url("../../../assets/images/index/服务查询/shixiaojiage_icon_wangdian.png") no-repeat;
}

.countBox {
  border: 1rpx solid #c4c4c4;
  border-radius: 8rpx;
  display: flex;
}

.nut-cell__value {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.resBox1 {
  border-radius: 16rpx;
  background: white;

  .bottomBorder {
    box-sizing: border-box;
    border-bottom: 2rpx solid rgb(214, 214, 214);
  }

  .resItem {
    height: 104rpx;
    padding: 28rpx 24rpx;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;

    .price {
      font-size: 28rpx;
      font-weight: 600;
    }

    p {
      font-size: 28rpx;
      color: #666666;
      margin-left: 12rpx;
    }

    image {
      height: 40rpx;
      width: 40rpx;
    }
  }

  .resBoxTop {
    color: #0966ff;
    background: url("../../../assets/images/index/服务查询/shixiaojiage_img_pujian.png") no-repeat;
    font-size: 32rpx;
    font-weight: 600;
  }
}

.resBox2 {
  border-radius: 16rpx;
  background: white;

  .bottomBorder {
    box-sizing: border-box;
    border-bottom: 2rpx solid rgb(214, 214, 214);
  }

  .resItem {
    height: 104rpx;
    padding: 28rpx 24rpx;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;

    .price {
      font-size: 28rpx;
      font-weight: 600;
    }

    p {
      font-size: 28rpx;
      color: #666666;
      margin-left: 12rpx;
    }

    image {
      height: 40rpx;
      width: 40rpx;
    }
  }

  .resBoxTop {
    color: #ff330a;
    background: url("../../../assets/images/index/服务查询/shixiaojiage_img_kuaijian.png") no-repeat;
    font-size: 32rpx;
    font-weight: 600;
  }
}

.bottomBoxFE {
  width: 100%;
  margin-top: 24rpx;
  display: flex;
  align-items: center;
  flex-direction: column;

  .mybtn {
    font-size: 32rpx;
    color: #fff;
    background-color: #0966ff;
    width: 700rpx;
    height: 88rpx;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .bottomP {
    font-size: 24rpx;
    line-height: 32rpx;
    color: #999;
    text-align: center;
    margin-top: 28rpx;
  }
}</style>
